package com.derbysoft.dswitch.adapter.ihg.common.repository.impl;

import com.derbysoft.dswitch.adapter.ihg.common.domain.HotelMapping;
import com.derbysoft.dswitch.adapter.ihg.common.domain.HotelStatus;
import com.derbysoft.dswitch.adapter.ihg.common.repository.HotelRepository;
import com.derbysoft.dswitch.adapter.ihg.web.action.support.Paginater;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("hotelService")
public class HotelRepositoryImpl extends CommonService<HotelMapping> implements HotelRepository {
    private static final String DERBY_CODE = "derbyCode";
    private static final String COOPERATOR_CODE = "cooperatorCode";
    private static final String HOTEL_NAME = "hotelName";
    private static final String STATUS = "status";

    @Override
    public void disableAll(List<HotelMapping> hotelMappings) {
        for (HotelMapping hotelMapping : hotelMappings) {
            hotelMapping.setStatus(HotelStatus.DISABLED);
            commonDao.save(hotelMapping);
        }
    }

    @Override
    public Paginater paginater(HotelMapping hotelMapping, Paginater paginater) {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(HotelMapping.class).addOrder(Order.desc("updateTime"));
        if (hotelMapping == null) {
            return super.paginater(detachedCriteria, paginater);
        }
        eq(detachedCriteria, DERBY_CODE, hotelMapping.getDerbyCode());
        eq(detachedCriteria, COOPERATOR_CODE, hotelMapping.getCooperatorCode());
        ilike(detachedCriteria, HOTEL_NAME, hotelMapping.getHotelName());
        eq(detachedCriteria, STATUS, hotelMapping.getStatus());
        return super.paginater(detachedCriteria, paginater);
    }

    @Override
    public HotelMapping loadByHotelCode(String hotelCode) {
        return load(new String[]{COOPERATOR_CODE}, new Object[]{hotelCode});
    }

    @Override
    public HotelMapping loadByHotelCode(String hotelCode, HotelStatus hotelStatus) {
        return load(new String[]{COOPERATOR_CODE, STATUS}, new Object[]{hotelCode, hotelStatus});
    }

    @Override
    public HotelMapping loadByDerbyCode(String derbyCode) {
        return load(new String[]{DERBY_CODE, STATUS}, new Object[]{derbyCode, HotelStatus.ENABLED});
    }

    @Override
    public void saveAll(List<HotelMapping> hotelMappings) {
        for (HotelMapping hotelMapping : hotelMappings) {
            super.commonDao.save(hotelMapping);
        }
    }
}
